<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useUserStore } from '@vben/stores';

defineOptions({ name: 'WatermarkWrapper' });

const userStore = useUserStore();

// 水印内容
const watermark = computed(() => {
  const userInfo = userStore.userInfo;
  return [userInfo?.nameCn, userInfo?.idCard, userInfo?.phone].join(' ');
});

const containerRef = ref<HTMLElement>();
let watermarkElement: HTMLElement | null = null;

// 创建水印
const createWatermark = () => {
  if (!containerRef.value) return;

  // 清除之前的水印
  if (watermarkElement) {
    watermarkElement.remove();
  }

  // 创建水印容器
  const watermarkDiv = document.createElement('div');
  watermarkDiv.className = 'watermark-overlay';

  // 设置水印样式
  watermarkDiv.style.cssText = `
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1000;
    background-image: repeating-linear-gradient(
      -45deg,
      transparent,
      transparent 100px,
      rgba(0, 0, 0, 0.1) 100px,
      rgba(0, 0, 0, 0.1) 120px
    );
    overflow: hidden;
  `;

  // 创建水印文本模式
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  if (ctx) {
    // 设置canvas大小 - 根据PDF水印的间距调整
    canvas.width = 400;
    canvas.height = 180;

    // 设置水印文本样式 - 与PDF水印保持一致
    ctx.font = '20px Arial'; // 与PDF水印字体大小一致
    ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'; // 与PDF水印透明度一致
    ctx.textAlign = 'center';
    ctx.translate(200, 90);
    ctx.rotate(-Math.PI / 6); // 旋转角度与PDF水印一致

    // 绘制水印文本
    ctx.fillText(watermark.value, 0, 0);

    // 将canvas转换为数据URL
    const dataURL = canvas.toDataURL();

    // 设置水印背景 - 使用与PDF水印类似的间距
    watermarkDiv.style.backgroundImage = `url(${dataURL})`;
    watermarkDiv.style.backgroundRepeat = 'repeat';
    watermarkDiv.style.backgroundSize = '400px 180px';
  }

  // 添加到容器
  containerRef.value.appendChild(watermarkDiv);
  watermarkElement = watermarkDiv;
};

// 监听容器大小变化，重新创建水印
const resizeObserver = new ResizeObserver(() => {
  createWatermark();
});

onMounted(() => {
  if (containerRef.value) {
    createWatermark();
    resizeObserver.observe(containerRef.value);
  }
});

onUnmounted(() => {
  if (watermarkElement) {
    watermarkElement.remove();
  }
  resizeObserver.disconnect();
});
</script>

<template>
  <div ref="containerRef" class="watermark-container flex items-center justify-center">
    <slot />
  </div>
</template>

<style lang="less" scoped>
.watermark-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

:deep(.watermark-overlay) {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
</style>
